package com.example.big_event.interceptor;

import com.example.big_event.utils.ThreadLocalUtil;
import com.example.big_event.utils.jwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.management.RuntimeErrorException;
import java.util.Map;

@Component//标记此拦截器作为元件，需要去配置类(WebConfig)中注册才能使用
public class Logininterceptor implements HandlerInterceptor {

    @Autowired//注解注入redis使用对象
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的令牌
        String token = request.getHeader("Authorization");

        //验证token
        try {

            //调用redis对象获取到token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String stringRedis = operations.get(token);

            //判断token是否为空
            if(stringRedis == null){

                //token失效了 抛出异常
                throw  new RuntimeException();
            }


            //  调用工具类中的解析方法解析token
            Map<String, Object> claims = jwtUtil.parse(token);//解析token

            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);

            return true; //放行
        } catch (Exception e) {
            //失败  拦截
            //http设置状态响应码为401
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
